import 'dart:async';
import 'package:aweb5/Constants.dart';
import 'package:flutter/material.dart';
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';
import 'package:aweb5/config/Config.dart';
import 'package:aweb5/util/JsonUtil.dart';
import 'package:fluttertoast/fluttertoast.dart';
//flutter_webview_plugin版，为解决 webview_flutter 在一个机型上返回首页后无法调用js方法的问题

class AplusHomePageVflutterwebviewplugin extends StatefulWidget {

  String id;

  AplusHomePageVflutterwebviewplugin(this.id);

  @override
  _AplusHomePageVflutterwebviewpluginState createState() =>
      _AplusHomePageVflutterwebviewpluginState();
}







final Set<JavascriptChannel> jsChannels = [
  JavascriptChannel(
      name: 'Print',
      onMessageReceived: (JavascriptMessage message) {
        print(message.message);
      }),
].toSet();


class _AplusHomePageVflutterwebviewpluginState
    extends State<AplusHomePageVflutterwebviewplugin> {

  int currentTab = 0;

  JavascriptChannel _alertJavascriptChannel2() {
    return JavascriptChannel(
        name: 'setTabSelect',
        onMessageReceived: (JavascriptMessage message) {
          print(">>>messagesettabselect");
          //  print(">>>message${message.message}");
          // Fluttertoast.showToast(msg: "1");
          if (message.message == "1") {
            currentTab = 0;
          }
          if (message.message == "2") {
            currentTab = 1;
          }
          if (message.message == "3") {
            currentTab = 2;
          }
          if (message.message == "4") {
            currentTab = 3;
          }
          if (message.message == "5") {
            currentTab = 4;
          }
          setState(() {});
        });
  }

  JavascriptChannel _alertJavascriptChannel3() {
    return JavascriptChannel(
        name: 'shareLinkToSession',
        onMessageReceived: (JavascriptMessage message) {
          print(">>>message");
          // toast("${message.message}");
          print(message.message);

          // String s ='{"title":"牛掰","desc":"12","link":"http://docker.hhn.weixin.local//#/product_share_order?product_sku_id=394&share_client_id=1&customer_id=5&api=api-ds","imgUrl":"http://aweb.oss-cn-hangzhou.aliyuncs.com/files/20191023144959866.jpg"}";

//          try {
//            Map<String, dynamic> map =
//            JsonUtil.json2map(message.message.toString());
//
//            print(">>>map${map["title"]}");
//            LinkEntity linkEntity = LinkEntity.fromJson(map);
//            print(">>>>>${linkEntity.imgUrl}");
//            fluwxUtil.shareLinktoSession(linkEntity.link, linkEntity.title,
//                linkEntity.imgUrl, linkEntity.desc);
//          } catch (e) {
//            print(">>>${e.toString()}");
//          }

          setState(() {});
        });
  }

  JavascriptChannel _alertJavascriptChannel4() {
    return JavascriptChannel(
        name: 'sharePosterToSession',
        onMessageReceived: (JavascriptMessage message) {
          print(">>>message");
          // toast("${message.message}");
          print(message.message);
//          FileUtil.saveBase64toGallery(message.message).then((v) {
//            // toast("${v}");
//            fluwxUtil.shareImagetoSession(v, v);
//          });

          setState(() {});
        });
  }

  JavascriptChannel _alertJavascriptChannel6() {
    return JavascriptChannel(
        name: 'sendAvatarUrl',
        onMessageReceived: (JavascriptMessage message) {
          print(">>>message");

          Fluttertoast.showToast(msg: "from h5");
//           toast("${message.message}");
//          print(message.message);
//          FileUtil.saveBase64toGallery(message.message).then((v) {
//            // toast("${v}");
//            fluwxUtil.shareImagetoSession(v, v);
//          });

          setState(() {});
        });
  }

  JavascriptChannel _alertJavascriptChannel7() {
    return JavascriptChannel(
      name: 'loginflutter',
      onMessageReceived: (JavascriptMessage message) {
        print(">>>messagelogin");
        // toast("${message.message}");
        print(message.message);
        Fluttertoast.showToast(msg: "login");
//          FileUtil.saveBase64toGallery(message.message).then((v) {
//            // toast("${v}");
//            fluwxUtil.shareImagetoSession(v, v);
//          });

//          setState(() {});
      },
    );
  }

  JavascriptChannel _alertJavascriptChannel5() {
    return JavascriptChannel(
        name: 'wxpay',
        onMessageReceived: (JavascriptMessage message) {
          print(">>>message");
          // toast("${message.message}");
          print(">>>${message.message}");
//          try {
//            Map<String, dynamic> map =
//            JsonUtil.json2map(message.message.toString());
//
//            print(">>>map${map["title"]}");
//            WxpayEntity linkEntity = WxpayEntity.fromJson(map);
//            fluwx
//                .payWithWeChat(
//                appId: linkEntity.appid,
//                partnerId: linkEntity.partnerid,
//                packageValue: linkEntity.package,
//                nonceStr: linkEntity.noncestr,
//                timeStamp: int.parse(linkEntity.timestamp),
//                sign: linkEntity.sign,
//                prepayId: linkEntity.prepayid)
//                .then((v) {
//              controller?.evaluateJavascript('orderList("1")')?.then((result) {
//                // Fluttertoast.showToast(msg: "1");
//                // You can handle JS result here.
//              });

//              print(v);
//            });
//          } catch (e) {
//            print(">>>${e.toString()}");
//          }
          setState(() {});
        });
  }


  final flutterWebViewPlugin = FlutterWebviewPlugin();
  StreamSubscription<String> _onUrlChanged;
  StreamSubscription<WebViewStateChanged> _onStateChanged;
  StreamSubscription<double> _onProgressChanged;
  StreamSubscription<WebViewHttpError> _onHttpError;
  String currentUrl = "";
  bool firstPage = true;
  bool iscenter = false;
  int index = 0;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _onUrlChanged = flutterWebViewPlugin.onUrlChanged.listen((String url) {
      if (mounted) {



        var v =  url;
        if(v.startsWith(Config.baseUrl)){

          if (!v.startsWith("${Config.baseUrl}#/classify") &&
              v != ("${Config.baseUrl}#/") &&
              !v.startsWith("${Config.baseUrl}#/member") &&
              !v.startsWith("${Config.baseUrl}#/cart") &&
              !v.startsWith("${Config.baseUrl}#/order") &&
              v != ("${Config.baseUrl}#/?kk=2")) {
            firstPage = false;
          } else {
            firstPage = true;
          }

          if (v == ("${Config.baseUrl}#/")) {
            currentTab = 0;
          }
          if (v.startsWith("${Config.baseUrl}#/cart")) {
            currentTab = 3;
          }
          if (v == ("${Config.baseUrl}#/?kk=2")) {
            currentTab = 0;
          }
          if (v.startsWith("${Config.baseUrl}#/order")) {
            currentTab = 4;
          }


//            controller
//                ?.evaluateJavascript('flutter_lod("${index}")')
//                ?.then((result) {});
//          width = 0;


          // _initLocation();
          setState(() {});


        }




        setState(() {
          currentUrl = url;
          print(">>>>>>>>>>>$url");
        });
      }
    });

    _onStateChanged =
        flutterWebViewPlugin.onStateChanged.listen((WebViewStateChanged state) {
          if (mounted) {







            flutterWebViewPlugin.evalJavascript('sendmemberid("${Constants.memberInfoEntity.data.memberId}")');

//            flutterWebViewPlugin.evalJavascript('sendmemberid("268687")');
            if(state == WebViewState.finishLoad&&currentUrl==Config.baseUrl){


            }


          }
        });
    _onProgressChanged =
        flutterWebViewPlugin.onProgressChanged.listen((double progress) {
          if (mounted) {
            setState(() {

            });
          }
        });
    _onHttpError =
        flutterWebViewPlugin.onHttpError.listen((WebViewHttpError error) {
          if (mounted) {
            setState(() {

            });
          }
        });
  }

  @override
  Widget build(BuildContext context) {
    return
      Scaffold(
        floatingActionButton: GestureDetector(
          onTap: () {

            flutterWebViewPlugin.evalJavascript('flutter("${2}")')?.then((result) {
              // You can handle JS result here.
            });

            currentTab = 100;
            setState(() {});
          },
          child: ClipRRect(
            borderRadius: BorderRadius.circular(50),
            child: FadeInImage.assetNetwork(
              width: 50,
              height: firstPage?150:0,
              placeholder: 'assets/touxiang.png',
              image: Constants.memberInfoEntity?.data.headimgurl,
              fit: BoxFit.cover,
            ),
          ),
        ),
        floatingActionButtonLocation:
        FloatingActionButtonLocation.centerDocked,
        body:WebviewScaffold(

          userAgent: "flutter",
          url: Config.baseUrl,
//        url: "https://www.baidu.com/",
          withJavascript: true,
          javascriptChannels: <JavascriptChannel>[

            _alertJavascriptChannel2(),
            _alertJavascriptChannel3(),
            _alertJavascriptChannel4(),
            _alertJavascriptChannel5(),
            _alertJavascriptChannel6(),
            _alertJavascriptChannel7(),


          ].toSet(),
          withZoom: true,
          withLocalStorage: true,
          hidden: true,
//          bottomNavigationBar: bottomAppBar(),

        ) ,
        bottomNavigationBar: bottomAppBar(),
      );


  }


  bool isFirstPage(String v) {
    if (v == ("${Config.baseUrl}#/login") ||
        v.startsWith("${Config.baseUrl}#/classify") ||
        v == ("${Config.baseUrl}#/") ||
        v.startsWith("${Config.baseUrl}#/member") ||
        v.startsWith("${Config.baseUrl}#/cart") ||
        v.startsWith("${Config.baseUrl}#/order") ||
        v.startsWith("${Config.baseUrl}#/?kk=2")) {
      return true;
    } else {
      return false;
    }
  }

  Widget bottomAppBar() {
    return Visibility(
        visible: firstPage,
        child: BottomAppBar(
          child: Padding(
            padding: EdgeInsets.fromLTRB(0, 6, 0, 6),
            child: Row(
              mainAxisSize: MainAxisSize.max,
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: <Widget>[
                GestureDetector(
                    onTap: () {
                      //  toast("${index}");

                      iscenter = false;
                      index = 0;
                      currentTab = index;
                      if (index > 2) {
                        //currentTab--;
                      }
                      setState(() {});

                      flutterWebViewPlugin.evalJavascript
                           ('flutter("${index}")')
                          ?.then((result) {
                        // You can handle JS result here.
                      });
                      print(">>>>${index}");
                    },
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      children: <Widget>[getIcon1(0), getTitle1(0)],
                    )),
                GestureDetector(
                    onTap: () {
                      //  toast("${index}");
                      index = 1;
                      currentTab = index;
                      if (index > 2) {
                        //currentTab--;
                      }
                      setState(() {});

                      flutterWebViewPlugin.evalJavascript('flutter("${index}")')
                          ?.then((result) {
                        // You can handle JS result here.
                      });
                      print(">>>>${index}");
                    },
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      children: <Widget>[getIcon1(1), getTitle1(1)],
                    )),
                GestureDetector(
                  onTap: () {
                    currentTab = 100;
                    flutterWebViewPlugin.evalJavascript('flutter("${2}")')
                        ?.then((result) {
                      // You can handle JS result here.
                    });
                    setState(() {});
                  },
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    children: <Widget>[
                      Icon(
                        Icons.home,
                        color: Colors.transparent,
                      ),
                      Text("个人中心", style: TextStyle(color: centerColor()))
                    ],
                  ),
                ),
                GestureDetector(
                    onTap: () {
                      //  toast("${index}");
                      index = 3;
                      currentTab = index;
                      if (index > 2) {
                        //currentTab--;
                      }
                      setState(() {});

                      flutterWebViewPlugin.evalJavascript('flutter("${index}")')
                          ?.then((result) {
                        // You can handle JS result here.
                      });
                      print(">>>>${index}");
                    },
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      children: <Widget>[getIcon1(3), getTitle1(3)],
                    )),
                GestureDetector(
                    onTap: () {
                      //  toast("${index}");
                      index = 4;
                      currentTab = index;
                      if (index > 2) {
                        //currentTab--;
                      }
                      setState(() {});

                      flutterWebViewPlugin.evalJavascript('flutter("${index}")')
                          ?.then((result) {
                        // You can handle JS result here.
                      });
                      print(">>>>${index}");
                    },
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      children: <Widget>[getIcon1(4), getTitle1(4)],
                    ))
              ],
            ),
          ),
        ));
  }
  Color centerColor() {
    if (currentTab == 100) {
      return Color(0xffce2020);
    } else {
      return Color(0xff100f0f);
    }
  }
  Widget getTitle1(int index) {
    if (index == 0) {
      if (currentTab == index) {
        return Text("首页",
            style: TextStyle(color: Color(0xffce2020), fontSize: 9));
      } else {
        return Text("首页",
            style: TextStyle(color: Color(0xff100f0f), fontSize: 9));
      }
    }
    if (index == 1) {
      if (currentTab == index) {
        return Text("分类",
            style: TextStyle(color: Color(0xffce2020), fontSize: 9));
      } else {
        return Text("分类",
            style: TextStyle(color: Color(0xff100f0f), fontSize: 9));
      }
    }

    if (index == 3) {
      if (currentTab == index) {
        return Text("购物车",
            style: TextStyle(color: Color(0xffce2020), fontSize: 9));
      } else {
        return Text("购物车",
            style: TextStyle(color: Color(0xff100f0f), fontSize: 9));
      }
    }
    if (index == 4) {
      if (currentTab == index) {
        return Text("订单",
            style: TextStyle(color: Color(0xffce2020), fontSize: 9));
      } else {
        return Text("订单",
            style: TextStyle(color: Color(0xff100f0f), fontSize: 9));
      }
    }
  }
  Widget getIcon1(int index) {
    if (index == 0) {
      if (currentTab == index) {
        return Container(
          width: 25,
          height: 25,
          alignment: Alignment.bottomCenter,
          child: Image.asset(
            "assets/nMenu-c1.png",
            width: 20.0,
            height: 20,
            fit: BoxFit.fill,
          ),
        );
      } else {
        return Container(
          width: 25,
          height: 25,
          alignment: Alignment.bottomCenter,
          child: Image.asset(
            "assets/nMenu-g1.png",
            width: 20.0,
            height: 20,
            fit: BoxFit.fill,
          ),
        );
      }
    }

    if (index == 1) {
      if (currentTab == index) {
        return Container(
          width: 25,
          height: 25,
          alignment: Alignment.bottomCenter,
          child: Image.asset(
            "assets/nMenu-c2.png",
            width: 20.0,
            height: 20,
            fit: BoxFit.fill,
          ),
        );
      } else {
        return Container(
          width: 25,
          height: 25,
          alignment: Alignment.bottomCenter,
          child: Image.asset(
            "assets/nMenu-g2.png",
            width: 20.0,
            height: 20,
            fit: BoxFit.fill,
          ),
        );
      }
    }

    if (index == 3) {
      if (currentTab == index) {
        return Container(
          width: 25,
          height: 25,
          alignment: Alignment.bottomCenter,
          child: Image.asset(
            "assets/nMenu-c3-1.png",
            width: 20.0,
            height: 20,
            fit: BoxFit.fill,
          ),
        );
      } else {
        return Container(
          width: 25,
          height: 25,
          alignment: Alignment.bottomCenter,
          child: Image.asset(
            "assets/nMenu-g3-1.png",
            width: 20.0,
            height: 20,
            fit: BoxFit.fill,
          ),
        );
      }
    }

    if (index == 4) {
      if (currentTab == index) {
        return Container(
          width: 25,
          height: 25,
          child: Stack(
            children: <Widget>[
              Container(
                width: 25,
                height: 25,
                alignment: Alignment.bottomCenter,
                child: Image.asset(
                  "assets/nMenu-c4.png",
                  width: 20.0,
                  height: 20.0,
                  fit: BoxFit.fill,
                ),
              ),
              Positioned(
                child: Text(""),
                right: 0,
                top: 0,
              )
            ],
          ),
        );
      } else {
        return Container(
          width: 25,
          height: 25,
          child: Stack(
            children: <Widget>[
              Container(
                width: 25,
                height: 25,
                alignment: Alignment.bottomCenter,
                child: Image.asset(
                  "assets/nMenu-g4.png",
                  width: 20.0,
                  height: 20.0,
                  fit: BoxFit.fill,
                ),
              ),
              Positioned(
                child: Text(""),
                right: 0,
                top: 0,
              )
            ],
          ),
        );
      }
    }
  }


  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();


    _onUrlChanged.cancel();
    _onStateChanged.cancel();
    _onHttpError.cancel();
    _onProgressChanged.cancel();
  }

}
